package spacecrack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@PersistenceCapable(detachable = "true")
public class Game {
	public static Key getKey(String id) {
		return KeyFactory.createKey(Game.class.getSimpleName(), id);
	}

	@PrimaryKey
	@Persistent
	private Key key;

	@Persistent
	private String name;

	@Persistent
	private Key owner;

	@Persistent
	private String status;

	@Persistent//(mappedBy = "game")
	private List<GameEvent> events = new ArrayList<GameEvent>();

	@Persistent
	private List<Key> playerKeys = new ArrayList<Key>();

	@NotPersistent
	private Map<Key, Player> players = new HashMap<Key, Player>();

	public Game(String id, String name, Key owner, String status) {
		this.key = getKey(id);
		this.name = name;
		this.owner = owner;
		this.status = status;
	}

	public Key getKey() { return key; }
	public String getName() { return name; }
	public Key getOwner() { return owner; }
	public String getStatus() { return status; }

	public List<GameEvent> getEvents() {
		if (events == null) return new ArrayList<GameEvent>();

		return new ArrayList<GameEvent>(events);
	}
	public GameEvent getEvent(int index) {
		return events.get(index);
	}
	public int getEventCount() {
		if (events == null) return 0;

		return events.size();
	}
	public void addEvent(GameEvent event) {
		events.add(event);
	}

	public List<Key> getPlayerKeys() {
		return new ArrayList<Key>(playerKeys);
	}
	public Key getPlayerKey(int index) {
		return playerKeys.get(index);
	}
	public int getPlayerKeyCount() {
		return playerKeys.size();
	}
	public void addPlayerKey(Key player) {
		playerKeys.add(player);
	}
	public void delPlayerKey(int index) {
		playerKeys.remove(index);
	}

	public List<Player> getPlayers() {
		if (players == null) players = new HashMap<Key, Player>();
		return new ArrayList<Player>(players.values());
	}
	public Player getPlayer(Key key) {
		if (players == null) players = new HashMap<Key, Player>();
		return players.get(key);
	}
	public void addPlayer(Player player) {
		if (players == null) players = new HashMap<Key, Player>();
		players.put(player.getKey(), player);
	}
	public void delPlayer(Player player) {
		if (players == null) players = new HashMap<Key, Player>();
		players.remove(player.getKey());
	}

	@Override
	public String toString() {
		return "[Game '"+ key +"' '"+ name +"' '"+ owner +"' '"+ status +"' "+ players +"]";
	}
}
